package com.ruoyi.crop.controller;

import com.ruoyi.common.core.web.controller.BaseController;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.core.web.page.TableDataInfo;
import com.ruoyi.common.security.utils.SecurityUtils;
import com.ruoyi.crop.api.domain.CropType;
import com.ruoyi.crop.api.domain.SignRecord;
import com.ruoyi.crop.api.domain.Warehouse;
import com.ruoyi.crop.service.WarehouseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@RestController
@RequestMapping("/warehouse")
public class WarehouseController extends BaseController {

    @Autowired
    WarehouseService warehouseService;

    /**
     * 获取仓库列表
     */
    @GetMapping("/list")
    public TableDataInfo list(Warehouse warehouse)
    {
        startPage();
        List<Warehouse> list = warehouseService.selectWarehouseList(warehouse);
        return getDataTable(list);
    }

    /**
     * 根据仓库编号获取详细信息
     */
    @GetMapping(value = "/{warehouseId}")
    public AjaxResult getInfo(@PathVariable Integer warehouseId)
    {
        return success(warehouseService.getById(warehouseId));
    }

    /**
     * 新增仓库
     */
    @PostMapping
    public AjaxResult add(@Validated @RequestBody Warehouse warehouse)
    {
        if (!warehouseService.checkWarehouseNameUnique(warehouse)){
            return error("新增仓库"+warehouse.getWarehouseName()+"失败,仓库已存在");
        }
        warehouse.setWarehouseCode("CR"+ UUID.randomUUID().toString().substring(0,8));
        warehouse.setCreateBy(SecurityUtils.getUsername());
        warehouse.setCreateTime(new Date());
        warehouse.setUserId(SecurityUtils.getUserId().intValue());
        return toAjax(warehouseService.save(warehouse));
    }

    /**
     * 修改仓库
     */
    @PutMapping
    public AjaxResult edit(@Validated @RequestBody Warehouse warehouse)
    {
        if (!warehouseService.checkWarehouseNameUnique(warehouse)){
            return error("新增仓库"+warehouse.getWarehouseName()+"失败,仓库已存在");
        }
        warehouse.setUpdateBy(SecurityUtils.getUsername());
        warehouse.setUpdateTime(new Date());
        return toAjax(warehouseService.updateById(warehouse));
    }

    /**
     * 删除仓库
     */
    @DeleteMapping("/{warehouseIds}")
    public AjaxResult remove(@PathVariable Integer[] warehouseIds)
    {
        return toAjax(warehouseService.removeBatchByIds(Arrays.asList(warehouseIds)));
    }

    /**
     * 根据仓库Id查询所有产品数据
     */
    @GetMapping("getProductsById")
    public AjaxResult getProductsById(Integer warehouseId){

       List<SignRecord> list = warehouseService.getProductsById(warehouseId);
       return success(list);
    }



}
